package com.homwee.factory;


import com.homwee.factory.util.Contants;
import com.homwee.tvap.common.comSettingInterface.factoryPage4;
import com.homwee.tvap.common.srvfunc.FactorySetting;
import com.mediatek.twoworlds.factory.MtkTvFApiDisplayTest;
import com.mediatek.twoworlds.factory.MtkTvFApiInformation;
import com.mediatek.twoworlds.tv.MtkTvUtil;

import android.app.Activity;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import com.mediatek.twoworlds.factory.MtkTvFApiSystem;
import com.mediatek.twoworlds.factory.common.MtkTvFApiSystemTypes;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//for local dimming vop pattern
import com.mediatek.twoworlds.factory.MtkTvFApiDisplayTest;
import com.mediatek.twoworlds.factory.model.MtkTvFApiDispTstPattern;

import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;

public class FactoryModeService extends Service {
	private static final String TAG = "FactoryService";
	private BroadcastReceiver stopBroadcastReceiver = null;
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		startForeground(0,null);
		//showBarCodePop();//show barcode
		IntentFilter filter = new IntentFilter();
		filter.addAction("android.intent.action.SCREEN_OFF");
		filter.addAction("android.intent.action.ACTION_SHUTDOWN");
		filter.addAction("com.homwee.action.STOP_FACTORY_SERVICE");
		filter.addAction(Intent.ACTION_HEADSET_PLUG);

		stopBroadcastReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				Log.d(TAG, "zcj Factory Service stopSelf"+intent.getAction());
				if(intent.getAction().equalsIgnoreCase("com.homwee.action.STOP_FACTORY_SERVICE")){
					stopSelf();
				}
				else if(intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)){
					Log.d(TAG,"zcj Factory Service stopSelf HEADSET_PLUG");
					int state = intent.getIntExtra("state", -1);
					if(state==1) {
						setVolume(60,context);
					}
				} else{
					setFactoryMMode(0);
					Settings.System.putInt(context.getContentResolver(), Contants.FACTORY_M_MODE_GO, 0);
					setAgingModel(0);
					//resetAutoEnterFactoryIni();
					stopSelf();
				}
			}
		};
		registerReceiver(stopBroadcastReceiver, filter);
		return START_NOT_STICKY;//START_STICKY;
	}
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		Log.d(TAG, "cz cyf test BarCodeService onDestroy");
		if(stopBroadcastReceiver != null)
			unregisterReceiver(stopBroadcastReceiver);
		android.os.Process.killProcess(android.os.Process.myPid());
		super.onDestroy();
	}
	
	private boolean setFactoryMMode(int mode) {
		boolean isSucces = false;
		isSucces = (MtkTvFApiInformation.getInstance()
		  .setIniParameter(Contants.PATH_FACTORYINI, Contants.FACTORY_M_MODE,
		  ""+mode) == -1) ? false : true;
        if(mode==0) {
			//MtkTvFApiSystem.getInstance().setFactoryPowerMode(MtkTvFApiSystemTypes.EnumSystemFactoryPowerMode.E_MTK_FAPI_SYSTEM_FACTORY_POWER_MODE_SECONDARY);
			FactorySetting.getInstance(getApplicationContext()).factoryResetPowerMode();
			//set skip wizard
            isSucces=(MtkTvFApiInformation.getInstance().setIniParameter(
					Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_SKIP_WIZARDSETUP, "" + mode) == -1) ? false
					: true;
	    		//turn off keypadTest
			MtkTvUtil.KeypadControl(0);
        }
        else{
            MtkTvFApiSystem.getInstance().setFactoryPowerMode(MtkTvFApiSystemTypes.EnumSystemFactoryPowerMode.E_MTK_FAPI_SYSTEM_FACTORY_POWER_MODE_DIRECT);
			//set skip wizard
            isSucces=(MtkTvFApiInformation.getInstance().setIniParameter(
					Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_SKIP_WIZARDSETUP, "" + mode) == -1) ? false
					: true;
			int picMode=Settings.Global.getInt(getApplicationContext().getContentResolver(), "picture_mode",0);
			Settings.Global.putInt(getApplicationContext().getContentResolver(), getBlackLightName(picMode),0);

			//set backlight & dreamTime
			int backlightInt=1;
			int dreamTimeInt=1;
			int twoHourInt=7200000;
			try{
				backlightInt = Settings.Global.getInt(getApplicationContext().getContentResolver(), "picture_backlight");
				dreamTimeInt=Settings.System.getInt(getApplicationContext().getContentResolver(), SCREEN_OFF_TIMEOUT);
			}catch (Settings.SettingNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(backlightInt!=100||dreamTimeInt!=twoHourInt){
				Settings.Global.putInt(getApplicationContext().getContentResolver(), "picture_backlight", 100);
				Settings.System.putInt(getApplicationContext().getContentResolver(), SCREEN_OFF_TIMEOUT, twoHourInt);
			}

        }
        return isSucces;
	}
	
	public void setAgingModel(int value) {
		// TODO Auto-generated method stub
		Log.v("tv", "in setAgingModel()");
		MtkTvFApiDisplayTest.getInstance().setBurningMode(value == 1 ? true : false);
		//VOP pattern
		MtkTvFApiDispTstPattern patternMode = new MtkTvFApiDispTstPattern();
		patternMode.mIsVopEnable = value==1?true:false;
		patternMode.mWindow = 0;
		int ret=MtkTvFApiDisplayTest.getInstance().generateTestPattern(6, patternMode);//
		Log.d("Testpattern",ret+"");
		if (value == 1) {
			MtkTvUtil.IRRemoteControl(4);
		} else {
			if(getLDMEnable()==1) {
				Log.d("factoryPage5.Testpattern", "finish");
				((Activity) TestImagePatternsActivity.mContext).finish();
			}
			MtkTvUtil.IRRemoteControl(3);
		}
		MtkTvFApiInformation.getInstance()
				.setIniParameter(Contants.KEYSTATUS_INI_FILEPATH,
						Contants.FACTORY_AGE_MODE, "" + value);
	}

	public void resetAutoEnterFactoryIni(){
		String enterFactoryDb=MtkTvFApiInformation.getInstance().getIniParameter(
				Contants.PATH_FACTORY_AUTOENTERFACTORY_INI, "FactoryDB:DB");
		if(enterFactoryDb.equals("1")){
			int ret=MtkTvFApiInformation.getInstance().setIniParameter(
					Contants.PATH_FACTORY_AUTOENTERFACTORY_INI, "FactoryDB:DB","0");
		}
	}


	public int getLDMEnable(){
		String enable=MtkTvFApiInformation.getInstance().getIniParameter(
				Contants.FACTORY_EXTRA_BOARD_PATH, Contants.FACTORY_LDM_ENABLE);
		int ret;
		if(TextUtils.isEmpty(enable)){
			ret=0;
		}else{
			ret=Integer.parseInt(enable);
		}
		return ret;
	}

	public void setVolume(int value ,Context context) {
		AudioManager audioManager = null;
		audioManager = (AudioManager) context
				.getSystemService(Context.AUDIO_SERVICE);
		if (audioManager != null) {
			audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, value,
					AudioManager.FLAG_PLAY_SOUND);
			try {
				Class c = Class.forName("android.media.AudioManager");
				Method m = c.getMethod("disableSafeMediaVolume");
				m.invoke(audioManager);
			} catch (InvocationTargetException e) {
				e.printStackTrace();
				Log.e("CHFactory.setVolume", "InvocationTargetException :" + e.toString());
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
				Log.e("CHFactory.setVolume", "NoSuchMethodException :" + e.toString());
			} catch (IllegalAccessException e) {
				e.printStackTrace();
				Log.e("CHFactory.setVolume", "IllegalAccessException :" + e.toString());
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
				Log.e("CHFactory.setVolume", "ClassNotFoundException :" + e.toString());
			}
		}
	}

	public String getBlackLightName(int pictureMode){
		String autoBackName;
		switch (pictureMode){
			case 0:
				autoBackName="key_picture_mode_user_auto_backlight";
				break;
			case 2:
				autoBackName="key_picture_mode_sport_auto_backlight";
				break;
			case 3:
				autoBackName="key_picture_mode_vivid_auto_backlight";
				break;
			case 7:
				autoBackName="key_picture_mode_standard_auto_backlight";
				break;
			case 9:
				autoBackName="key_picture_mode_movie_auto_backlight";
				break;
			case 10:
				autoBackName="key_picture_mode_game_auto_backlight";
				break;
			case 11:
				autoBackName="key_picture_mode_energy_saving_auto_backlight";
				break;
			default:
				autoBackName="key_picture_mode_others_auto_backlight";
				break;
		}
		return autoBackName;
	}
}
